package com.ruoyi.web.controller.stepnumber;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.stepnumber.domain.userInfo;
import com.ruoyi.stepnumber.domain.WxLoginInfo;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;

/**
 * 微信步数 信息操作处理
 * 
 * @author lzy
 * @date 2019年4月14日
 */
@Controller
@RequestMapping("/wxauth")
public class WxAuthController extends BaseController {
	
	
	@Autowired
	private WxMaService wxService;
	
	
	
	
	
	
	  /**
	   * 微信登陆
	   * @param wxLoginInfo
	   * @param request
	   * @return
	   */
	@RequestMapping("login_by_weixin")
	@ResponseBody
	public AjaxResult loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) {
		String code = wxLoginInfo.getCode();
		int upperId = wxLoginInfo.getUpperId();
		userInfo userInfo = wxLoginInfo.getUserInfo();
		if (code == null || userInfo == null) {
			return error("参数错误！！");
		}
		String sessionKey = null;
		String openId = null;
		
		try {
			WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
			sessionKey = result.getSessionKey();
			openId = result.getOpenid();
			return success(sessionKey);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (sessionKey == null || openId == null) {
			return error();
		}
		return null;
	
	/*	
		LitemallUser user = userService.queryByOid(openId);
		// 开启事务管理
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		try {
			if (user == null) {
				String NickName = null;
				String replaceNickName = userInfo.getNickName().replaceAll("[\\x{10000}-\\x{10FFFF}]", "");
				try {
					NickName  = URLEncoder.encode(userInfo.getNickName(),"utf-8");
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				user = new LitemallUser();
				user.setUsername(NickName);
				user.setPassword(openId); 
				user.setWeixinOpenid(openId);
				user.setAvatar(userInfo.getAvatarUrl());
				user.setNickname(replaceNickName);
				user.setGender(userInfo.getGender());
				user.setUserLevel((byte) 4);
				user.setStatus((byte) 0);
				user.setLastLoginTime(LocalDateTime.now());
				user.setLastLoginIp(IpUtil.client(request));
				user.setAddTime(LocalDateTime.now());
				LitemallUser resuser = null;
				Integer[] userIds = { upperId };
				if(upperId !=0){
					//邀请注册				
					resuser = userService.findById(upperId);
					if(resuser ==null){
						user.setMyupper(1);//非分享注册  直接转移至管理员下级
						//消息通知(发送给代理级别的推荐人) 
						Integer[] userByAdmin = {1};
						notifyService.saveDaiLi(userByAdmin,replaceNickName);
					}else {
						if(resuser.getUserLevel() == 4){
							user.setMyupper(resuser.getMyupper());
							//消息通知(发送给客户级别的推荐人)  					
							notifyService.saveKehu(userIds,replaceNickName);
						}else{
							user.setMyupper(upperId);
							//消息通知(发送给代理级别的推荐人) 
							notifyService.saveDaiLi(userIds,replaceNickName);
						}
					}
							
				}else {
					user.setMyupper(1);//非分享注册  直接转移至管理员下级
					//消息通知(发送给代理级别的推荐人) 
					Integer[] userByAdmin = {1};
					notifyService.saveDaiLi(userByAdmin,replaceNickName);
				}
				
				int add = userMapper.insertSelective(user);
					
				//邀请人增加社交星
				if(add == 0){
					throw new Exception("网络异常，请稍后再试");
				}else {
					//消息通知(发送给新注册用户)
					Integer[] userIdss = {user.getId()};
					notifyService.saveSuccess(userIdss,userService.findById(user.getMyupper()).getNickname());
					LitemallUser litemallUser = new LitemallUser();
					if(upperId != 0){
						litemallUser.setId(upperId);
						litemallUser.setSuyongstar(resuser.getSuyongstar() + 1);
						userService.updateById(litemallUser);
					}
					
					
				}
				
			} 
			
		} catch (Exception ex) {
			txManager.rollback(status);
			logger.error("系统内部错误", ex);
			return ResponseUtil.fail(403, "网络异常，请稍后再试");
		}
		
		txManager.commit(status);
		
		// token
		UserToken userToken = UserTokenManager.generateToken(user.getId());
		userToken.setSessionKey(sessionKey);
		
		// userInfo
				UserInfo userInfo1 = new UserInfo();
				String decode = null;
				try {
					decode = URLDecoder.decode(user.getUsername(), "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				userInfo1.setNickName(decode);
				userInfo1.setAvatarUrl(user.getAvatar());
				userInfo1.setTotalScore(user.getTotalScore());
				userInfo1.setLevelName(Conts.getLevelName(user.getUserLevel()));
				userInfo1.setGender(user.getGender());
				userInfo1.setSuyongstar(user.getSuyongstar());
				userInfo1.setId(user.getId());
				userInfo1.setBalance(user.getBalance());
				
				//查询该用户排名
				Map<String, Object> map = new HashMap<>();
				map.put("totalScore", user.getTotalScore());
				map.put("userLevel", user.getUserLevel());
				int rankByLevel= userMapper.getRankByLevel(user.getUserLevel());//查询等级数量
				int rankByscore = userMapper.getRankByscore(map);//查询等级及小于积分的数量
				userInfo1.setRank(rankByLevel-rankByscore);
				

		Map<Object, Object> result = new HashMap<Object, Object>();
		result.put("token", userToken.getToken());
		result.put("tokenExpire", userToken.getExpireTime().toString());
		result.put("userInfo", userInfo1);
		*/
		
		
	}
    
	
	
	
	
	
}
